package cn.git.future;

import java.util.concurrent.*;

/**
 * @description: 两个任务完成其中任意一个任务
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-08-07
 */
public class CompletableFutureDemo09 {

    static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            5,
            50,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 没有返回结果，串行执行任务
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程1执行了：" + Thread.currentThread().getName());
            return 50;
        }, executor);

        // 串行执行任务
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("子线程3执行了：" + Thread.currentThread().getName());
            return 100;
        }, executor).exceptionally((e) -> {
            // 线程3执行结果作为线程4入参参数
            System.out.println("子线程4执行了：" + Thread.currentThread().getName());
            System.out.println("子线程4执行异常了：" + e.getMessage());
            return -1;
        });

        // 两个任务完成其中任意一个任务,便开始执行，带有任意一个执行完毕参数信息
        future1.acceptEitherAsync(future2, (res) -> {
            System.out.println("新线程：" + Thread.currentThread().getName());
            System.out.println("获取任意结果：" + res);
        }, executor);
    }
}
